package org.moonshiner.controller.dao.hibernate;

import java.lang.reflect.ParameterizedType;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import org.moonshiner.controller.dao.BaseDao;

@SuppressWarnings("unchecked")
public abstract class GenericDao<T> extends HibernateDaoSupport implements
		BaseDao<T> {

	public GenericDao(SessionFactory sessionFactory) {
		setHibernateTemplate(new HibernateTemplate(sessionFactory));
	}

	public T get(Integer id) {
		return (T) getHibernateTemplate().get(getEntityClass(), id);
	}

	public T save(T entity) {
		Integer id = (Integer) getHibernateTemplate().save(entity);
		return (T) getHibernateTemplate().get(getEntityClass(), id);
	}

	public T update(T entity) {
		getHibernateTemplate().update(entity);
		return entity;
	}

	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	public void delete(Integer id) {
		T entity = (T) getHibernateTemplate().get(getEntityClass(), id);
		getHibernateTemplate().delete(entity);
	}

	public Class<?> getEntityClass() {
		return ((Class) ((ParameterizedType) getClass().getGenericSuperclass())
				.getActualTypeArguments()[0]);
	}

}
